package com.lujianfei.powersearch.ui.createOrUpdate.viewmodel

import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lujianfei.powersearch.ui.createOrUpdate.model.AppInfoBean
import com.lujianfei.powersearch.utils.SystemUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class AppSelectViewModel: ViewModel() {

    val showLoading = ObservableField(true)
    val showEmpty = ObservableField(false)
    val emptyText = ObservableField("未找到")
    private val originalList = arrayListOf<AppInfoBean>()
    val appList = ObservableArrayList<AppInfoBean>()

    var onItemClickCallback: ((AppInfoBean) -> Unit)?= null
    val onItemClick: ((AppInfoBean) -> Unit) = {
        onItemClickCallback?.invoke(it)
    }

    fun load() {
        viewModelScope.launch(Dispatchers.Main) {
            showLoading.set(true)
            val packageManager = SystemUtils.getApplicationContext().packageManager
            val response=  withContext(Dispatchers.IO) {
                packageManager?.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES)?.let {
                    for (app in it) {
                        if ((app.flags and ApplicationInfo.FLAG_SYSTEM) <= 0) {
                            val bean = AppInfoBean()
                            bean.flags = app.flags
                            bean.icon = app.loadIcon(packageManager)
                            bean.name = app.loadLabel(packageManager).toString()
                            bean.packageName = app.packageName
                            bean.searchKey = "${bean.name}${bean.packageName}"
                            originalList.add(bean)
                        }
                    }
                }
                originalList
            }
            showLoading.set(false)
            appList.addAll(response)
            showEmpty.set(false)
        }
    }

    fun search(searchText: String) {
        if (searchText.isBlank()) {
            appList.clear()
            appList.addAll(originalList)
            showEmpty.set(false)
            return
        }
        originalList.filter { it.name?.lowercase()?.contains(searchText.lowercase()) == true ||
                it.packageName?.lowercase()?.contains(searchText.lowercase()) == true}.let {
            appList.clear()
            appList.addAll(it)
        }

        showEmpty.set(appList.isEmpty())
        emptyText.set("找不到'$searchText'")
    }
}